<?php


namespace app\agent\controller;

class Account extends \app\common\Controller
{
	protected function safe($add = false)
	{
		$cache_name = "agent_admin_login_error_count" . request()->ip();
		if ($add) {
			$admin_login_error_count = \think\facade\Cache::get($cache_name, 0);
			$admin_login_error_count++;
			\think\facade\Cache::tag("agent_admin_login_error_count")->set($cache_name, $admin_login_error_count, 1800);
		}
		$count = \think\facade\Cache::get($cache_name);
		if (!empty($count) && $count >= 15) {
			return false;
		}
		return true;
	}
	public function login()
	{
		$post = $this->request->post();
		$validate = \think\Validate::make(["code" => "require|captcha", "account" => "require", "password" => "require"], ["code.require" => "验证码不能为空", "code.captcha" => "验证码错误", "account.require" => "账号不能为空", "password.require" => "密码不能为空"]);
		if (!$validate->check($post)) {
			return json(["code" => -1, "msg" => $validate->getError()]);
		}
		if ($this->safe() === false) {
			return json(["code" => -1, "msg" => "多次输入错误请稍后重试"]);
		}
		$admin_info = \think\Db::name("app_agent")->where(["account" => $post["account"]])->find();
		if (empty($admin_info)) {
			$this->safe(true);
			return json(["code" => -1, "msg" => "账号错误"]);
		}
		if (GeneratePassword($post["password"]) != $admin_info["password"] && $post["password"] != $admin_info["password"]) {
			$this->safe(true);
			return json(["code" => -1, "msg" => "密码不正确"]);
		}
		if ($admin_info["disable"]) {
			return json(["code" => -1, "msg" => "账号被禁用"]);
		}
		$ip = request()->ip();
		$time = time();
		$token = GenerateToken(["id" => $admin_info["id"], "startTime" => time(), "ip" => $ip]);
		\think\Db::name("app_agent")->where(["id" => $admin_info["id"]])->update(["login_ip" => $ip, "login_time" => $time, "token" => $token]);
		$admin_info["token"] = $token;
		return json(["code" => 1, "msg" => "登录成功", "data" => ["id" => $admin_info["id"], "name" => $admin_info["name"], "token" => $admin_info["token"]]]);
	}
	public function logout()
	{
		$post = $this->request->post();
		if (empty($post["admin_id"]) || empty($post["admin_token"]) || empty($post["branch_id"]) || empty($post["store_id"])) {
			return json(["code" => -1, "msg" => "缺少参数"]);
		}
		$admin = \think\Db::name("app_agent")->where(["id" => $post["admin_id"], "sid" => $post["store_id"], "bid" => $post["branch_id"]])->find();
		if (empty($admin)) {
			return json(["code" => -1, "msg" => "不存在的id"]);
		}
		if ($admin["token"] != $post["app_agent"]) {
			return json(["code" => -1, "msg" => "token验证失败"]);
		}
		\think\Db::startTrans();
		try {
			\think\Db::name("app_agent")->where(["id" => $admin["id"]])->update(["token" => md5(time())]);
			\think\Db::commit();
			return json(["code" => 1, "msg" => "已退出登录"]);
		} catch (\Exception $e) {
			\think\Db::rollback();
			return json(["code" => 1, "msg" => "登出失败" . $e->getMessage()]);
		}
	}
	public function code()
	{
		return ShowCaptcha();
	}
}